package com.wwm.makerandroid.makerandroid.View.Fragment;


import static com.wwm.makerandroid.makerandroid.Utils.ParseUtil.getStateString;
import static com.wwm.makerandroid.makerandroid.Utils.ParseUtil.getTypeString;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.widget.CardView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lipiao.makerandroid.R;
import com.wwm.makerandroid.makerandroid.Bean.RespondBean.MessageBean;

import com.wwm.makerandroid.makerandroid.Bean.RespondBean.RecordBean;
import com.wwm.makerandroid.makerandroid.Bean.RespondBean.TempBean;
import com.wwm.makerandroid.makerandroid.Bean.ViewBean.ApplyBean;
import com.wwm.makerandroid.makerandroid.Bean.ViewBean.LeaveClearance;
import com.wwm.makerandroid.makerandroid.Utils.HttpUtil;
import com.wwm.makerandroid.makerandroid.View.Adapter.MyImageView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.Objects;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


//原始的四个碎片自带缓存 无需懒加载 也不会重复加载数据
public class ClearanceFragment extends Fragment {

    View rootView;
    static String userNumber;//账号
    String applyId;

    //    健康码
    Button upjiankangma;
    EditText jiangkangmaPathEd;
    MyImageView sukangmaImg;
    //行程信息
    Button xingchengmaBt;
    EditText xingchengPathEd;
    MyImageView xingchengImg;
    String approverId;
    //    核算信息
    Button heshuanBt;
    EditText heshuanPathEd;
    MyImageView heshuanImg;
    //提交按钮
    Button UploadClearanceBT;

    //        上传成功后的网络地址
    String jiankangImgUrl = "https://img0.baidu.com/it/u=3487108568,2054368074&fm=253&fmt=auto&app=138&f=JPG?w=700&h=434";
    String xingchengImgUrl = "https://img0.baidu.com/it/u=3487108568,2054368074&fm=253&fmt=auto&app=138&f=JPG?w=700&h=434";
    String hesuanImgUrl = "https://img0.baidu.com/it/u=3487108568,2054368074&fm=253&fmt=auto&app=138&f=JPG?w=700&h=434";
    //    上传失败初始显示的图片地址
//    String initialUrl = "https://img0.baidu.com/it/u=3487108568,2054368074&fm=253&fmt=auto&app=138&f=JPG?w=700&h=434";
    String imgUrl;
    //最近的未销假的请求
    ApplyBean lastUnsoldApply;
    protected TextView applyType;
    protected TextView detail;
    protected TextView state;
    protected TextView time;
    protected TextView remark;
    protected CardView apply;
    View unsoldView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }


    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_clearance, container, false);
        unsoldView = rootView.findViewById(R.id.tv_apply_state);
        applyType = unsoldView.findViewById(R.id.tv_apply_type);
        detail = unsoldView.findViewById(R.id.tv_detail);
        state = unsoldView.findViewById(R.id.tv_apply_state);
        time = unsoldView.findViewById(R.id.tv_top_article_time);
        remark = unsoldView.findViewById(R.id.tv_remark);
        apply = unsoldView.findViewById(R.id.cv_top_record_card);

//绑定相关的布局
        upjiankangma = rootView.findViewById(R.id.jiangkangma_upload);
        jiangkangmaPathEd = rootView.findViewById(R.id.img_path);
        sukangmaImg = rootView.findViewById(R.id.jiankangmaImg);

        xingchengmaBt = rootView.findViewById(R.id.xingchengma_upload);
        xingchengPathEd = rootView.findViewById(R.id.xingcheng_img_path);
        xingchengImg = rootView.findViewById(R.id.xingchengImg);

        heshuanBt = rootView.findViewById(R.id.heshuan_upload);
        heshuanPathEd = rootView.findViewById(R.id.heshuan_img_path);
        heshuanImg = rootView.findViewById(R.id.heshuanImg);
        UploadClearanceBT=rootView.findViewById(R.id.uploadClearanceApply);

//        sukangmaImg.setImageURL(initialUrl);
//        sukangmaImg.setImageURL(initialUrl);
//        sukangmaImg.setImageURL(initialUrl);
//        设置三个上传按钮的监听
        upjiankangma.setOnClickListener(mOnClickListener);
        heshuanBt.setOnClickListener(mOnClickListener);
        xingchengmaBt.setOnClickListener(mOnClickListener);
//        设置提交按钮的监听
        UploadClearanceBT.setOnClickListener(mOnClickListener);
//        详情
        applyType = rootView.findViewById(R.id.tv_apply_type);
        detail = rootView.findViewById(R.id.tv_detail);
        state = rootView.findViewById(R.id.tv_apply_state);
        time = rootView.findViewById(R.id.tv_top_article_time);
        remark = rootView.findViewById(R.id.tv_remark);
        getLastApplyDetail();
        return rootView;
    }


    public static ClearanceFragment newInstance(String username) {
        ClearanceFragment fragment = new ClearanceFragment();
        Bundle bundle = new Bundle();
        userNumber = username;
        bundle.putString("userNumber", username);
        fragment.setArguments(bundle);
        return fragment;
    }

    private View.OnClickListener mOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.jiangkangma_upload://上传健康吗
//                    /sdcard/Pictures/3.jpeg
                    String path;
                    path = jiangkangmaPathEd.getText().toString();
                    System.out.println("健康"+path);
                    if (path != null) {
                        jiankangImgUrl=uploadImage(path, sukangmaImg, "健康");

                    }
                    break;
                //todo 其他信息
                case R.id.xingchengma_upload:////上传行程信息
                    String path2;
                    path2 = xingchengPathEd.getText().toString();
                    System.out.println("健康"+path2);
                    if (path2 != null) {
                        xingchengImgUrl=  uploadImage(path2, xingchengImg, "行程");
                    }
                    break;
                case R.id.heshuan_upload:////上传核算信息
                    String path3;
                    path3 = heshuanPathEd.getText().toString();
                    System.out.println("健康"+path3);
                    if (path3 != null) {
                        hesuanImgUrl= uploadImage(path3, heshuanImg, "核酸");
                    }
                    break;
                case R.id.uploadClearanceApply://提交销假表单
                    Gson gson = new Gson();
                        LeaveClearance leaveClearance=new LeaveClearance(lastUnsoldApply.getId(),
                            jiankangImgUrl,xingchengImgUrl,hesuanImgUrl,lastUnsoldApply.getApproverId());
                    RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), gson.toJson(leaveClearance));
                    Call<MessageBean> call = HttpUtil.getUserService().addClearanceApply(requestBody);

                    call.enqueue(new Callback<MessageBean>() {
                        @Override
                        public void onResponse(Call<MessageBean> call, Response<MessageBean> response) {
                    Toast.makeText(getContext(), "提交销假申请成功!", Toast.LENGTH_LONG).show();
                        }

                        @Override
                        public void onFailure(Call<MessageBean> call, Throwable t) {
                            Toast.makeText(getContext(), "提交销假申请失败!", Toast.LENGTH_LONG).show();

                        }
                    });
            }
    }};


    //    参考链接：https://blog.csdn.net/u013758734/article/details/39504075
//    https://blog.csdn.net/qq_40543575/article/details/79232311
//    上传行程，核酸，行程等图片，都用这段
//需要提前将文件放到 /sdcard/Pictures/目录下 且格式要一样 .jpeg
//    上传图片

    /**
     * @param myImageView 设置上传后的图片在哪显示
     * @param prefx       告诉后台传过来的文件是什么种类 我没找到更优雅的方式 因为requestBody 为MultipartBody格式。 不方便加别的变量
     *                    就将文件名加上前缀 到后台再分割出来
     */

    private String uploadImage(String path, MyImageView myImageView, String prefx) {
//在手机完整路径
//        /storage/emulated/0/Pictures/11.jpeg
        String fullPath = "/sdcard/Pictures/" + path + ".jpeg";
//        File file = new File("/sdcard/Pictures/3.jpeg");
        File file = new File(fullPath);
        // 根据文件的后缀名，获得文件类型
//        String fileType = getMimeType(file.getName());
//        RequestBody requestBody = RequestBody.create(picture);
//    上传文件都得封装成MultipartBody 格式
        MultipartBody.Builder requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM);
        if (file != null) {
          try {
              // MediaType.parse() 里面是上传的文件类型。
              RequestBody body = RequestBody.create(MediaType.parse("image/*"), file);

              // 参数分别为， 请求key ，文件名称 ， RequestBody
              requestBody.addFormDataPart("file", prefx + file.getName(), body);
          }catch (Exception e){
              System.out.println(e+"大概率文件不存在");
             return "" ;
          }
        }


        Call<MessageBean> call = HttpUtil.getUserService().uploadFile(requestBody.build());
        call.enqueue(new Callback<MessageBean>() {


            @Override
            public void onResponse(Call<MessageBean> call, Response<MessageBean> response) {
                String  strBack = (String) response.body().getData();
                System.out.println("strBack-----"+strBack);
                if(strBack!=null){
                    imgUrl=strBack;
                Objects.requireNonNull(getActivity()).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
//为什么要写在这里？而不是再别的地方加载图片？
// 应为响应成功是返回的是网络地址  请求网络地址需要时间 写到这里新开个线程 不影响主线程运行
// 简单来说就是异步加
                        System.out.println("strBack++++"+strBack);
                        myImageView.setImageURL(strBack);
                    }
                });
            }}

            @Override
            public void onFailure(Call<MessageBean> call, Throwable t) {
                System.out.println(t);
            }
        });
        return imgUrl;
    }

    //获取上一个没有销假的申请
    void getLastApplyDetail() {
        Call<ResponseBody> call = HttpUtil.getUserService().getLastNotClearanceApply(userNumber);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String strBack = response.body().string();
                    //处理数据
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(strBack);
                    Gson gson = new Gson();

                    lastUnsoldApply = gson.fromJson(jsonObject.toString(), TempBean.class).getData();
                    if (lastUnsoldApply == null) {
                        return;
                    }
                    //将获取到的未销假信息记录绑定显示显示
                    state.setText("未销假");
                    applyId=lastUnsoldApply.getApproverId();


                    applyType.setText(getTypeString(lastUnsoldApply.getType()));
                    //未通过审核的就将其备注信息颜色设为红色
                    detail.setText(lastUnsoldApply.getReason());
                    remark.setText(lastUnsoldApply.getRemark());
                    time.setText("从" + lastUnsoldApply.getOutDate().substring(0, 16) + " 到 " + lastUnsoldApply.getExpectedReturnDate().substring(0, 16));

                    Objects.requireNonNull(getActivity()).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                        }
                    });
                } catch (JSONException e) {
                    System.out.println(e);

                } catch (IOException e) {
                    System.out.println(e);
                    e.printStackTrace();
                }

            }


            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
            }
        });
    }
}